<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools>
        <template #left>总记录条数：100条</template>
        <el-button
          v-check="'POINT-USER-IMPORT'"
          size="small"
          type="success"
          @click="$router.push('/import?type=employee')"
        >导入</el-button>
        <el-button size="small" type="warning" @click="exportExcel">导出</el-button>
        <el-button size="small" type="primary" @click="showDialog = true">新增员工</el-button>
      </PageTools>
      <el-card v-loading="loading">
        <el-table border :data="list">
          <el-table-column label="序号" align="center" type="index" width="120" />
          <el-table-column label="头像" align="center">
            <template v-slot="{row}">
              <img
                v-imgerror="require('@/assets/common/bigUserHeader.png')"
                width="80px"
                height="80px"
                style="object-fit: cover"
                :src="row.staffPhoto"
                alt=""
                @click="showCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="姓名" align="center" prop="username" />
          <el-table-column label="工号" align="center" prop="workNumber" />
          <el-table-column label="聘用形式" align="center">
            <template v-slot="{row}">
              <!-- 硬编码 -->
              {{ row.formOfEmployment === 1 ? '正式': '非正式' }}
            </template>
          </el-table-column>
          <!-- <el-table-column
            label="聘用形式"
            align="center"
            prop="formOfEmployment"
            :formatter="formatEmployment"
          /> -->
          <el-table-column label="部门" align="center" prop="departmentName" />
          <el-table-column label="入职时间" align="center">
            <template v-slot="{row}">
              {{ row.timeOfEntry | time }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态">
            <template v-slot="{row}">
              <!-- {{ row.enableState === 1 ? '可用': '禁用' }} -->
              <el-switch
                :value="row.enableState === 1"
                active-color="#13ce66"
                inactive-color="#ff4949"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280">
            <template v-slot="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="assign(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="del(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row type="flex" justify="end" style="margin-top: 20px;">
          <el-pagination
            layout="prev, pager, next, jumper"
            :total="total"
            background
            :page-size="size"
            :current-page="page"
            @current-change="changeFn"
          />
        </el-row>
      </el-card>
      <AddEmployee :show-dialog.sync="showDialog" />
      <el-dialog title="二维码" :visible.sync="showCodeDialog" width="30%">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <!-- 分配角色 -->
      <AssignRole :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
    </div>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import employeeEnum from '@/api/constant/employees'
import AddEmployee from '@/views/employees/components/add-employee'
import moment from 'moment'
import QrCode from 'qrcode'
import AssignRole from '@/views/employees/components/AssignRole.vue'
export default {
  name: 'Employees',
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      // 存放数据
      list: [],
      // 分页相关
      page: 1,
      // 存储总数量
      total: 0,
      size: 5,
      loading: false,
      hireType: employeeEnum.hireType,
      showDialog: false,
      showCodeDialog: false,
      showRoleDialog: false,
      userId: ''
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {

    async getEmployeeList() {
      this.loading = true
      const data = await getEmployeeList(this.page, this.size)
      // console.log(data)
      this.total = data.total
      this.list = data.rows
      this.loading = false
    },
    changeFn(value) {
      this.page = value
      this.getEmployeeList()
    },
    formatEmployment(row, column, cellValue, index) {
      if (cellValue === null) {
        return '其他'
      }
      return this.hireType.find(item => item.id === +cellValue).value
    },
    async del(id) {
      try {
        await this.$confirm('您确定要删除该员工吗', '温馨提示', { type: 'warning' })
      } catch {
        return
      }
      console.log('11111')
      await delEmployee(id)
      this.getEmployeeList()
      this.$message.success('删除员工成功')
    },
    exportExcel() {
      import('@/utils/Export2Excel').then(async excel => {
        const userRelations = {
          '姓名': 'username',
          '手机号': 'mobile',
          '入职日期': 'timeOfEntry',
          '转正日期': 'correctionTime',
          '工号': 'workNumber',
          '聘用形式': 'formOfEmployment',
          '部门': 'departmentName'
        }
        const multiHeader = [
          ['姓名', '主要信息', '', '', '', '', '部门']
        ]
        const merges = ['A1:A2', 'B1:F1', 'G1:G2']
        const tHeader = Object.keys(userRelations)
        // 发送ajax请求-获取所有的员工数据

        const { rows } = await getEmployeeList(1, 1000)
        // console.log(data) // rows从data解构
        const tData = rows.map(item => {
          return tHeader.map(k => {
            if (k === '入职日期' || k === '转正日期') {
              let time = item[userRelations[k]]
              if (time) {
                time = moment(item[userRelations[k]]).format('YYYY-MM-DD')
              }
              return time
            } else if (k === '聘用形式') {
              const result = employeeEnum.hireType.find(v => v.id === +item[userRelations[k]])
              return result ? result.value : '其他'
            } else {
              return item[userRelations[k]]
            }
          })
        })
        // const tData = []
        // rows.forEach(item => {
        //   // console.log(item)
        //   const arr = []
        //   Object.values(userRelations).forEach(k => {
        //     console.log(k)
        //     arr.push(item[k])
        //   })
        //   tData.push(arr)
        // })
        console.log(tData)
        // header: excel表头
        // data: 需要写入excel的数据
        // filename： 保存的文件名
        // autoWidth: excel的列是否自动设置宽度
        // bookType: 后缀名
        excel.export_json_to_excel({
          header: tHeader,
          multiHeader,
          // 配置合并
          merges,
          data: tData,
          filename: '员工数据',
          autoWidth: true,
          bookType: 'xlsx'
        })
      })
    },
    async showCode(photo) {
      this.showCodeDialog = true
      await this.$nextTick()
      QrCode.toCanvas(this.$refs.myCanvas, photo)
    },
    assign(id) {
      this.userId = id
      this.showRoleDialog = true
    }
  }

}
</script>

<style>

</style>

